#!/usr/bin/env python
# -*- coding: utf-8 -*-
from common.models.member.MemberCart import MemberCart

__author__ = 'ethereal'
__mtime__ = '2018/8/31'

from web.controllers.api import route_api
from  flask import request,jsonify,g
from common.models.food.FoodCat import FoodCat
from common.models.food.Food import Food
# from common.models.member.MemberCart import MemberCart
# from common.models.member.MemberComments import MemberComments
from common.models.member.Member import Member
from common.libs.UrlManager import UrlManager
# from common.libs.Helper import getCurrentDate,getDictFilterField,selectFilterObj
from application import app,db
from sqlalchemy import  or_

#小程序接口 返回banner图和首页的分类信息
@route_api.route("/food/index" )
def foodIndex():
    #定义统一返回数据格式
    resp = { 'code':200 ,'msg':'操作成功~','data':{} }
    #取到所有可以展示分类的分类列表
    cat_list = FoodCat.query.filter_by( status = 1 ).order_by( FoodCat.weight.desc() ).all()
    #返回数据格式构造
    data_cat_list = []
    data_cat_list.append({
        'id': 0,
        'name': "全部"
    })
    #如果查询到了直接遍历
    if cat_list:
        for item in cat_list:
            tmp_data = {
                'id':item.id,
                'name':item.name
            }
            #类别数据
            data_cat_list.append( tmp_data  )
    resp['data']['cat_list'] = data_cat_list
    #是取销售量最大的商品
    food_list = Food.query.filter_by( status = 1 )\
        .order_by( Food.total_count.desc(),Food.id.desc() ).limit(3).all()

    data_food_list = []
    if food_list:
        for item in food_list:
            tmp_data = {
                'id':item.id,
                'pic_url':UrlManager.buildImageUrl( item.main_image )
            }
            #构造轮播图数据
            data_food_list.append( tmp_data )

    resp['data']['banner_list'] = data_food_list
    return jsonify( resp )

#返回相关搜索信息
@route_api.route("/food/search" )
def foodSearch():
    #设置返回值
    resp = {'code': 200, 'msg': '操作成功~', 'data': {}}
    req = request.values#获取请求参数
    #分类id
    cat_id = int( req['cat_id'] ) if 'cat_id' in req else 0
    #获取搜索字符串
    mix_kw = str(req['mix_kw']) if 'mix_kw' in req else ''
    p = int( req['p'] ) if 'p' in req else 1  #获取当前分页

    if p < 1:
        p = 1

    page_size = 10
    offset = ( p - 1 ) * page_size
    #只查询状态是正常的数据
    query = Food.query.filter_by(status=1 )
    # 传递分类id>0 直接查询
    if cat_id > 0:
        query = query.filter_by(cat_id = cat_id)
    #如果有搜索字段 进行like查询
    if mix_kw:
        rule = or_(Food.name.ilike("%{0}%".format(mix_kw)), Food.tags.ilike("%{0}%".format(mix_kw)))
        query = query.filter(rule)
    #商品列表
    food_list = query.order_by(Food.total_count.desc(), Food.id.desc())\
        .offset( offset ).limit( page_size ).all()
    #定义前端返回数据结构
    data_food_list = []
    if food_list:
        for item in food_list:
            tmp_data = {
                'id': item.id,
                'name': "%s"%( item.name ),
                'price': str( item.price ),
                'min_price':str( item.price ),
                'pic_url': UrlManager.buildImageUrl(item.main_image)
            }
            data_food_list.append(tmp_data)
      #定义返回的对象
    resp['data']['list'] = data_food_list
    #是否还有下一次
    resp['data']['has_more'] = 0 if len( data_food_list ) < page_size else 1
    return jsonify(resp)


#商品详情接口
@route_api.route("/food/info" )
def foodInfo():
    resp = {'code': 200, 'msg': '操作成功~', 'data': {}}
    req = request.values
    #获取请求id
    id = int(req['id']) if 'id' in req else 0
    food_info = Food.query.filter_by( id = id ).first()
    if not food_info or not food_info.status :
        resp['code'] = -1
        resp['msg'] = "美食已下架"
        return jsonify(resp)

    member_info = g.member_info
    cart_number = 0
    if member_info:
        cart_number = MemberCart.query.filter_by( member_id =  member_info.id ).count()
    resp['data']['info'] = {
        "id":food_info.id,
        "name":food_info.name,
        "summary":food_info.summary,
        "total_count":food_info.total_count,
        "comment_count":food_info.comment_count,
        'main_image':UrlManager.buildImageUrl( food_info.main_image ),
        "price":str( food_info.price ),
        "stock":food_info.stock,
        "pics":[ UrlManager.buildImageUrl( food_info.main_image ) ]
    }
    resp['data']['cart_number'] = cart_number
    return jsonify(resp)

